/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.migrate;

import com.wtkj.exception.BusinessException;
import com.wtkj.vo.RandomGUID;
import com.wtkj.vo.dzzf.base.kfwd.Account;
import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wtkj.vo.dzzf.base.kfwd.FundAccount;
import com.wtkj.vo.dzzf.base.kfwd.UserInfoOpt;
import com.wtkj.vo.dzzf.share.staticvalue.AccountStaticValue;
import com.wttech.dzzf.process.dao.ImportHisDataDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.model.user.User;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 业务账户处理服务实现
 *
 * @author MaShibo
 * @date 2017/12/10.
 */
@Service("accoutHisDataProcess")
public class AccountProcessService {

	/**
	 * 账户为个人用户
	 */
	private static final String PERSON = "P_";
	/**
	 * 账户为单位用户
	 */
	private static final String UNIT = "U_";

	private static final String UNIT02 = "U02";

	private static final String PERSON02 = "P02";

	private static final int CLIENTID_SEQNO_LENGTH = 8;

	@Resource
	private ImportHisDataDao importHisDataDao;

	@Resource
	private BaseInfoService baseInfoService;

	@Resource(name = "cardHisDataProcess")
	private CardInfoProcessService cardInfoProcessService;

	@Resource
	private TransferUserInfoDao transferUserInfoDao;


	void process(Account account, FundAccount fundAccount) {
		String accountId = account.getAccountId();

		String accountNo = baseInfoService.generateAccountNo(fundAccount.getAccountType());
		String clientId = generateClientId(fundAccount.getOwnerType());
		importHisDataDao.updateAccountNoAndClientId(accountId, accountNo, clientId);
		importHisDataDao.updateAccountOptNo(accountId, accountNo);
		importHisDataDao.updateAccountOptTradeNo(accountId, new RandomGUID().ToRawString());

		List<CardInfo> cardInfos = importHisDataDao.queryCardInfosByAccountId(accountId);
		cardInfos.forEach(cardInfo -> cardInfoProcessService.process(cardInfo));
	}


	private String generateClientId(Integer ownerType) {
		String clientId = ownerType != null && ownerType == AccountStaticValue.AccountOwnType.OwnerType_Company ? UNIT : PERSON;
		String sequenceName = "SEQUENCE" + clientId + "CLIENTID";
		Long seqNo = importHisDataDao.querySequenceNo(sequenceName);
		StringBuilder seqNoStr = new StringBuilder(seqNo.toString());
		while (seqNoStr.length() < CLIENTID_SEQNO_LENGTH) {
			seqNoStr.insert(0, "0");
		}
		String newClientId = ownerType != null && ownerType == AccountStaticValue.AccountOwnType.OwnerType_Company ? UNIT02 : PERSON02;
		seqNoStr.insert(0, newClientId);
		return seqNoStr.toString();
	}

}
